package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Reader;
import java.util.Date;

/**
 * @Discription: 保存淘宝换货卖家发货确认收货 同步回执
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/01/11 10:00
 */
@Slf4j
@Component
public class SaveExchangeMsgService {

    /**
     * 保存淘宝换货卖家发货确认收货回执消息
     * @param jsonArray
     */
    @Synchronized
    public void saveExchange(JSONArray jsonArray) {

            // 更改状态
            String updateSql = "update t_omsrefundorder set returngoodconfirm = ? where id = ?";

            for (Object obj : jsonArray) {
                // 获取id
                JSONObject tempJsonObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                Long id = tempJsonObj.getLongValue("ID");
                boolean issuccess = tempJsonObj.getBoolean("issuccess");

                if (issuccess) {
                    // 回传成功,修改状态 1 成功   2 失败, 保存到日志表
                    QueryEngine.getInstance().executeUpdate(updateSql, new Object[]{1,id});
                    this.setRefundOrderLogs(id,"成功");
                } else {
                    // 调用接口失败,修改状态为 2 ,调用失败.保存日志到日志表,
                    String errcode = tempJsonObj.getString("error_code");
                    String errmsg = tempJsonObj.getString("error_msg");
                    // 修改视图状态为调用失败
                    QueryEngine.getInstance().executeUpdate(updateSql, new Object[]{2,id});
                    // 保存到日志表
                    this.setRefundOrderLogs(id,"失败");
                }
            }
    }

    /**
     * 保存换货卖家确认收货 日志
     * @param reid
     * @param logmessage
     */
    public void setRefundOrderLogs(Long reid,String logmessage){

        String retStr = "接口回写";
        String typeStr = "淘宝卖家收货确认";
        String squnceSql = "select get_wsequences('T_OMSRefundOrderLogs') as SEQ from dual";
        int id = TypeUtils.castToInt(QueryEngine.getInstance().doQueryOne(squnceSql));
        String insertSql = "insert into T_OMSRefundOrderLogs (id,omsrefundorderid,usercode,logtype,logmessage,ownerid,modifierid,modifieddate) values (?,?,?,?,?,?,?,?)";
        QueryEngine.getInstance().executeUpdate(insertSql,new Object[]{id,reid,retStr,typeStr,logmessage,retStr,retStr,new Date(System.currentTimeMillis())});

    }

}
